import Core from "./Core";
let wx = window['wx']

const { ccclass, property } = cc._decorator;
@ccclass
export default class WxUtil extends cc.Component {
    static bannerAd: any = null;
    static videoAd: any = null;
    static interstitialAd: any = null;
    static gridAd: any = null
    //格子广告是否加载成功
    static gridAdLoaded: boolean = true;

    static BANNER_ID: string = "adunit-6f4bec5e36a78510"
    static VIDEO_ID: string = "adunit-16ecb045e2b0821a"
    static CHAPIN_ID: string = "adunit-a4fce0d262a3324a"
    static GRID_ID: string = "adunit-6bd733d1425b3e23"


    public static share(callback = null) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.shareAppMessage({
                title: '这关太难了，快来帮帮我！',
                imageUrl: cc.loader.getRes('icon.png'),
                success: () => {
                    if (callback) {
                        callback()
                    }
                },
                fail: () => {

                }
            })
        }
    }
    static onShow(callback) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.onShow(function () {
                if (callback) {
                    callback();
                }
            })
        }
    }
    static showShareMenu(): void {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.showShareMenu({
                withShareTicket: true
            })
            wx.onShareAppMessage(function () {
                return {
                    title: '这关太难了，快来帮帮我！',
                    imageUrl: 'icon.png'
                }
            })
        }
    }
    static jump(appid): void {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.navigateToMiniProgram({
                appId: appid,
                path: '',
                extraData: null,
                envVersion: 'release',
                success(res) {
                    console.log('跳转成功');
                }
            })
        }
    }
    static showTip(value: string) {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            wx.showToast({ title: value, icon: 'none', duration: 1500 })
        }
    }
    static destroyBanner(): void {
        if (WxUtil.bannerAd != null) {           
            WxUtil.bannerAd.destroy()
            WxUtil.bannerAd = null;
        }
    }
   
    static showBanner(): void {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            
            var isIPX = false;
            wx.getSystemInfo({
                success: function (res) {
                    if (res.model.search('iPhone X') != -1) {
                        isIPX = true
                       
                    }
                }
            })
            let offsetY = 0;
            if (isIPX) {
                offsetY = -30
                //  return
            }
            
            
            let winSize = wx.getSystemInfoSync();
            let bannerHeight = 80;
            let bannerWidth = 300;
            let bannerAd = wx.createBannerAd({
                adUnitId: WxUtil.BANNER_ID,adIntervals:30,               
                style: {
                    left: (winSize.windowWidth - bannerWidth) * 0.5,
                    top: winSize.windowHeight - bannerHeight + offsetY,
                    width: bannerWidth
                }
            })
            WxUtil.bannerAd = bannerAd;
            WxUtil.bannerAd.show();
            //微信缩放后得到banner的真实高度，从新设置banner的top 属性
            bannerAd.onResize(res => {
                bannerAd.style.top = winSize.windowHeight - bannerAd.style.realHeight + offsetY;
            })

            // bannerAd.onError(err => {
            //     // 进行适当的提示
            //     console.log("banner显示", err);
            // })
        }
    }
    static initInterstitialAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {

            if (wx.createInterstitialAd) {
                WxUtil.interstitialAd = wx.createInterstitialAd({ adUnitId: WxUtil.CHAPIN_ID })
                WxUtil.interstitialAd.onLoad(() => {
                    console.log('插屏初始化成功')
                })
                WxUtil.interstitialAd.onError((err) => {
                    console.log('interstitialAd onError event emit', err)
                })
                WxUtil.interstitialAd.onClose((res) => {
                    console.log('interstitialAd onClose event emit', res)
                })

            }
        }
    }
    static showInterstitialAd() {
        if (WxUtil.interstitialAd) {
            console.log('显示插屏广告')
            WxUtil.interstitialAd.show().catch((err) => {
                console.error("插屏显示错误", err)
            })
        }

    }
    static initGridAd() {
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            let winSize = wx.getSystemInfoSync();
            if (wx.createGridAd) {
                let gridAd = wx.createGridAd({
                    adUnitId: WxUtil.GRID_ID,
                    gridCount: 5,
                    style: {
                        left: (winSize.windowWidth - 300) * 0.5,
                        top:  winSize.windowHeight-80,
                        width: 300,
                        opacity: 0.9
                    }
                })
                gridAd.onError((err) => {
                    console.log('格子广告初始化错误', err);
                    if (err['errCode'] >= 1000 && err['errCode'] <= 1008) {
                        WxUtil.gridAdLoaded = false;
                    }
                });
                WxUtil.gridAd = gridAd;

            }
        }


    }
    static showGridAd() {
        if (WxUtil.gridAd) {
            WxUtil.gridAd.show().catch((err) => {
                console.error('格子广告显示错误', err)
            })
        }
    }
    static destroyGrid(): void {
        if (WxUtil.gridAd != null) {
            WxUtil.gridAd.destroy()
            WxUtil.gridAd = null;
        }
    }
    static showVideo(): void {
        WxUtil.videoAd.show()
            .catch(() => {
                WxUtil.videoAd.load()
                    .then(() => WxUtil.videoAd.show())
                    .catch(err => {
                        console.log('激励视频 广告显示失败', err)
                        WxUtil.showTip('暂无视频可用！')

                        Core.dispatcher.execute('wxVideoEvent', 0)
                    })
            })
    }
    static initVideo(): void {

        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            if (WxUtil.videoAd != null) {
                return;
            }

            let videoAd = wx.createRewardedVideoAd({ adUnitId: WxUtil.VIDEO_ID })
            WxUtil.videoAd = videoAd

            videoAd.onLoad(() => {
                console.log('激励视频 广告加载成功')
            })

            videoAd.onError(err => {
                console.log(err)
                Core.dispatcher.execute('wxVideoEvent', 0)
            })

            videoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {

                    Core.dispatcher.execute('wxVideoEvent', 1)
                }
                else {
                    // 播放中途退出，不下发游戏奖励
                    Core.dispatcher.execute('wxVideoEvent', 0)
                }

            });
        }
    }
}
